<template>
  <van-radio-group class="g-question" v-bind="$attrs" v-on="$listeners">
    <van-cell-group :title="title">
      <van-cell
        v-for="option in items"
        :key="option.value"
        :title="option.label"
        :class="option.className"
        :value="option.text"
        clickable
        @click="setValue(option)"
      >
        <template v-if="!disabled" #right-icon>
          <van-radio :name="option.value" />
        </template>
      </van-cell>
    </van-cell-group>
  </van-radio-group>
</template>

<script>
import { RadioGroup, Radio, Cell, CellGroup } from 'vant'

export default {
  components: {
    [RadioGroup.name]: RadioGroup,
    [Radio.name]: Radio,
    [Cell.name]: Cell,
    [CellGroup.name]: CellGroup
  },
  inheritAttrs: false,
  props: {
    title: {
      type: String,
      default: ''
    },
    answer: {
      type: String,
      default: ''
    },
    correct: {
      type: String,
      default: ''
    },
    options: {
      type: Array,
      default: () => []
    },
    disabled: {
      type: Boolean,
      default: false
    }
  },
  computed: {
    items() {
      if (!this.answer) {
        return this.options
      }
      return this.options.map(option => {
        const right = this.correct === option.value
        const wrong = this.answer === option.value && this.answer !== this.correct
        const text = this.setText(option.value, right, wrong)
        return {
          ...option,
          text,
          className: {
            'van-cell--success': right,
            'van-cell--error': wrong
          }
        }
      })
    }
  },
  methods: {
    setValue(option) {
      if (this.disabled) {
        return
      }
      this.$emit('input', option.value)
    },
    setText(value, right, wrong) {
      let text = ''
      if (right && value === this.answer) {
        text = '回答正确'
      } else if (right) {
        text = '正确答案'
      } else if (wrong) {
        text = '回答错误'
      }
      return text
    }
  }
}
</script>

<style lang="less">
.g-question {
  padding: 0 12px;
  .van-cell-group__title {
    color: #333333;
    font-size: 32px;
    padding-left: 0;
  }

  .van-cell--success {
    background-color: #f6ffed;

    .van-cell__value {
      color: #52c41a;
    }
  }

  .van-cell--error {
    background-color: #fff2f0;
    .van-cell__value {
      color: #ff4d4f;
    }
  }

  .van-cell__value {
    flex: unset;
    white-space: nowrap;
    flex-shrink: 0;
  }

  .option(@index, @name) {
    &:nth-child(@{index})::before {
      content: @name;
    }
  }

  .van-cell {
    line-height: 80px;
    &::before {
      width: 40px;
      font-weight: bold;
    }
    &::after {
      left: 0;
      right: 0;
    }
    .option(1, 'A.');
    .option(2, 'B.');
    .option(3, 'C.');
    .option(4, 'D.');
    .option(5, 'E.');
    .option(6, 'F.');
  }
}
</style>
